import { useState, useEffect } from "react";
import * as events from './events';
import * as api from './api';
import Little from './components/little';

export interface IListItem {
  id: number;
  value: string;
}

export type IListState = [IListItem[], React.Dispatch<React.SetStateAction<IListItem[]>>];

export interface ICtx {
  editingId: [number, React.Dispatch<React.SetStateAction<number>>],
  list: IListState;
  showingList: IListState;
}

function createList (this: ICtx): JSX.Element[] {
  const [showingList] = this.showingList;
  const [editingId] = this.editingId;

  return showingList.map((item) => {
    return (
      <li key={ item.id }>
        {
          editingId === item.id
          ? <>
              <input type="text" id="edit" defaultValue={ item.value } />
              <button onClick={ () => events.onEditOk.call(this) }>确认</button>
            </>
          : <>
              { item.value }
              <button onClick={ () => events.onEdit.call(this, item.id) }>修改</button>
            </>
        }
        <button onClick={ () => events.onDelete.call(this, item.id) }>删除</button>
      </li>
    );
  });
}

export default function (this: any) {
  const ctx: ICtx = {
    editingId: useState<IListItem['id']>(-1),
    list: useState<IListItem[]>([]),
    showingList: useState<IListItem[]>([]),
  };

  // useEffect(() => {
  //   // componentDidMount
  //   (async () => {
  //     // 发请求
  //     const res = await api.getData();
  //     // 拿DOM
  //     const inp = document.querySelector('#inp');
  //     console.log(res, inp);
  //   })();
  // }, []);

  // useEffect(() => {
  //   // 接近于componentDidUpdate，componentDidUpdate是没有首次打印的
  //   console.log(1);
  // });

  // useEffect(() => {
  //   return () => {
  //     // componentWillUnmount
  //   };
  // }, []);

  const [visible, setVisible] = useState<boolean>(true);

  useEffect(() => {
    setTimeout(() => {
      // console.log(!visible);
      setVisible(!visible);
    }, 500);
  }, [visible]);

  return (
    <div className="App">
      { visible && <Little /> }
      {/* <input id="inp" type="text" />
      <button onClick={ () => events.onCreate.call(ctx) }>新增</button>
      <button onClick={ () => events.onSearch.call(ctx) }>查询</button>
      <ul>{ createList.call(ctx) }</ul> */}
    </div>
  );
}
